package com.hjx.http;

import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CookieBuilder {

    public static Map<String, String> getEqualMap(String cookieline) {
        Map<String, String> equalMap = new HashMap<>();
        String[] searchedStrings = searchByRegex(cookieline, "([^ ;,]+=[^ ;,]+)");
        for (String groupString : searchedStrings) {
            //这里不用 split 的原因是有可能等号后的值字符串中出现等号
            String[] equalStrings = new String[2];
            int equalCharIndex = groupString.indexOf("=");
            equalStrings[0] = groupString.substring(0, equalCharIndex);
            equalStrings[1] = groupString.substring(equalCharIndex + 1, groupString.length());
            if (equalStrings.length == 2) {
                String key = equalStrings[0];
                String value = equalStrings[1];
                if (value.startsWith("\"") && value.endsWith("\"")) {
                    value = value.substring(1, value.length() - 1);
                }
                equalMap.put(key, value);
            }
        }
        return equalMap;
    }

    public static String[] searchByRegex(String source, String regex) {
        if (source == null) {
            return null;
        }

        Map<Integer, Pattern> regexPattern = new HashMap<>();

        Pattern pattern = null;
        if (regexPattern.containsKey(regex.hashCode())) {
            pattern = regexPattern.get(regex.hashCode());
        } else {
            pattern = Pattern.compile(regex);
            regexPattern.put(regex.hashCode(), pattern);
        }
        Matcher matcher = pattern.matcher(source);
        ArrayList<String> result = new ArrayList<>();
        while (matcher.find()) {
            result.add(matcher.group());
        }
        return result.toArray(new String[0]);
    }

    @Test
    public void cookieStr2Map(){
        Map<String, String> cookies = getEqualMap(".ybtj.189.cn=7565001FFB1A1DF73768CBD31CE8027C; EcsCaptchaKey=QpwsCs7KVjJi5HYEJ3KOmASiq%2FPHnHinLOWzGxzFYHficxIm6hMSiw%3D%3D; EcsLoginToken=LUkcg8GxPTeMc7fE0H8vPdMsOQbEssQlP%2B4GNfcrjxLj1cNWRDn9vemjZ0zBWT6kVYyvmtLHqTzTJlWuJrFdGe9dmEl1jUGPEb6t2E51W10vMUNqJwKYuQ%3D%3D; EcsToLoginPara=zBPyOxHfMwekoO0uXkKvuYa0LkztAQUH9AUvwZjYZJPnvKJzXGmsLlDI%2BGG9XW7TrJ42b7F0hetMR3XpATnwsOP9UqZ95gStItJSSMofsz5qL04gO9u3bx1TxMnjZBAAKXpBhr1Ysx%2B7HeHDBrxNwf2HGc8XOQnmBUY8c91MqsB6As%2FeorNunovOAoZU74RTY3eqDj6KNFFULPrl3vttYm5EvLpJtPOZg%2F3NF%2BJjsPA%3D; SHOPID_COOKIEID=10001; aactgsh111220=18911568334; isLogin=logined; userId=201%7C138984432");
        System.out.println(cookies);
    }
}
